<?php

namespace App\Controller\Admin;

use App\Model\Admin;
use App\Services\JWTService;

class AccountController extends BaseController
{
    public function login(): array|\Psr\Http\Message\ResponseInterface
    {
        $tel = $this->request->post('username','');
        $password = $this->request->post('password','');
        if(empty($tel) || empty($password)){
            return $this->error('参数不完整');
        }
        $data = Admin::query()->where('username',$tel)->where('password',$password)->first();
        if(empty($data)){
            return $this->error('账号或密码错误');
        }
        Admin::query()->where('id',$data->id)->update(['last_login_time' => date('Y-m-d H:i:s')]);
        Admin::query()->where('id',$data->id)->update(['last_login_ip' => $this->request->getServerParams()['remote_addr']]);
        $data = $data->toArray();
        unset($data['password']);
        $token = JWTService::encode($data);
        return $this->success(['token' => $token]);
    }

    /**
     * 管理员信息
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function info(): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json([
            'code' => 0,
            'data' => $this->request->user
        ]);
    }

    /**
     * 获取管理员列表
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function list(): \Psr\Http\Message\ResponseInterface
    {
        [$skip, $pageSize] = $this->getSkipPageSize();
        $data = Admin::query()
            ->skip($skip)
            ->take($pageSize)
            ->orderBy('id','desc')
            ->select('id','nickname', 'username', 'avatar','last_login_time', 'last_login_ip', 'create_time')
            ->get()
            ->toArray();
        return $this->success($data);
    }

}